import { SwapRightOutlined, WarningTwoTone } from '@ant-design/icons';
import { ProCard } from '@ant-design/pro-components';
import { Badge, Collapse, CollapseProps, message, Tag, Typography } from 'antd';
import React, { useState } from 'react';
import styles from './DetailMonitorArticleContent.less';
const { Panel } = Collapse;
interface DetailMonitorArticleContentProps {
  name: string;
  content: string;
  errorWords: any[];
  onRefurbish: () => void;
}

const DetailMonitorArticleContent: React.FC<DetailMonitorArticleContentProps> = ({
  name,
  content,
  errorWords,
  onRefurbish,
}) => {
  const [html, setHtmlValueState] = useState<string>(content);
  const [checks, setCheckState] = useState<MonitorhcData.GreenTextInspectWords[]>(errorWords);
  const visibleChecks = checks;
  const checkItems = [];
  const errorItems = [];

  visibleChecks.forEach((item) => {
    if (item.inspectCategory === '可疑') {
      checkItems.push(item);
    } else if (item.inspectCategory === '错误') {
      errorItems.push(item);
    }
  });
  /**
   * 词 标记
   */
  const wordMark = (positioningId: string) => {
    const original = html
      .replaceAll(
        `class="${styles['word-mark-error-highlight-major']}"`,
        `class="${styles['word-mark-error-major']}"`,
      )
      .replaceAll(
        `class="${styles['word-mark-error-highlight-critical']}"`,
        `class="${styles['word-mark-error-critical']}"`,
      )
      .replaceAll(
        `class="${styles['word-mark-error-highlight-blocker']}"`,
        `class="${styles['word-mark-error-blocker']}"`,
      )
      .replaceAll(
        `class="${styles['word-mark-right-highlight']}"`,
        `class="${styles['word-mark-right']}"`,
      );

    visibleChecks.forEach((item: MonitorhcData.GreenTextInspectWords) => {




      const inspectCategory = item.inspectCategory;

      if (`#word${item.positioningId}`.includes(positioningId)) {
        item.click = 1;

        let errorWord = '';
        let errorWordHighlight = '';

        const inspectTypeEn = item.inspectTypeEn;

        // switch (inspectTypeEn) {
        //   case 'traditionalchinese': //繁简误用
        //   case 'variantchar': //异体字检查
        //   case 'transerror': //译文检查
        //   case 'terms': //不规范名词检查
        //   case 'keywords': //重点词检查
        //   case 'ADtime': //公元纪年错误
        //   case 'historytime': //历史纪年错误
        //   case 'branchtime': //干支纪年错误
        //   case 'placenameused': //地名检查（曾用名）
        //   case 'placenamematch': //地名检查（新旧地名不匹配）
        //   case 'placenamedivision': //地名检查（所属区 划错误）
        //   case 'placenamelevel': //地名检查（层级错误）
        //   case 'nonrecommender': //非推荐词
        //   case 'errorspace': //多余空格
        //     //一般
        //     errorWord = `id="word${item.positioningId}" class="${styles['word-mark-error-major']}"`;
        //     errorWordHighlight = `id="word${item.positioningId}" class="${styles['word-mark-error-highlight-major']}"`;
        //     break;
        //   case 'errorwords': //易错词检查
        //   case 'grammar': //语法检查
        //   case 'englishmodel': //英文检查
        //   case 'sentivewords': //敏感词检查
        //   // case 'punctuation': //标点符号检查
        //   case 'semrepetition': //语义重复
        //   case 'politicalterms': //涉政用语错误
        //     //严重
        //     errorWord = `id="word${item.positioningId}" class="${styles['word-mark-error-critical']}"`;
        //     errorWordHighlight = `id="word${item.positioningId}" class="${styles['word-mark-error-highlight-critical']}"`;
        //     break;
        //   case 'leadername': //领导人姓名检查
        //   case 'leadersort': //领导人排序检查
        //   case 'leadertitle': //领导人职务检查
        //   case 'politicalman': //提及政要
        //     //崩溃
        //     errorWord = `id="word${item.positioningId}" class="${styles['word-mark-error-blocker']}"`;
        //     errorWordHighlight = `id="word${item.positioningId}" class="${styles['word-mark-error-highlight-blocker']}"`;
        //     break;
        // }
        if (inspectCategory === '错误') {
          errorWord = `id="word${item.positioningId}" class="${styles['word-mark-error-blocker']}"`;
          errorWordHighlight = `id="word${item.positioningId}" class="${styles['word-mark-error-highlight-blocker']}"`;
          setHtmlValueState(original.replace(errorWord, errorWordHighlight));
        } else {
          errorWord = `id="word${item.positioningId}" class="${styles['word-mark-error-major']}"`;
          errorWordHighlight = `id="word${item.positioningId}" class="${styles['word-mark-error-highlight-major']}"`;
          console.log(inspectTypeEn);

          // switch (inspectTypeEn) {
          //   case 'traditionalchinese': //繁简误用
          //   case 'variantchar': //异体字检查
          //   case 'transerror': //译文检查
          //   case 'terms': //不规范名词检查
          //   case 'keywords': //重点词检查
          //   case 'ADtime': //公元纪年错误
          //   case 'historytime': //历史纪年错误
          //   case 'branchtime': //干支纪年错误
          //   case 'placenameused': //地名检查（曾用名）
          //   case 'placenamematch': //地名检查（新旧地名不匹配）
          //   case 'placenamedivision': //地名检查（所属区 划错误）
          //   case 'placenamelevel': //地名检查（层级错误）
          //   case 'nonrecommender': //非推荐词
          //   case 'errorspace': //多余空格
          //     //一般
          //     errorWord = `id="word${item.positioningId}" class="${styles['word-mark-error-major']}"`;
          //     errorWordHighlight = `id="word${item.positioningId}" class="${styles['word-mark-error-highlight-major']}"`;
          //     break;
          //   case 'errorwords': //易错词检查
          //   case 'grammar': //语法检查
          //   case 'englishmodel': //英文检查
          //   case 'sentivewords': //敏感词检查
          //   // case 'punctuation': //标点符号检查
          //   case 'semrepetition': //语义重复
          //   case 'politicalterms': //涉政用语错误
          //     //严重
          //     errorWord = `id="word${item.positioningId}" class="${styles['word-mark-error-critical']}"`;
          //     errorWordHighlight = `id="word${item.positioningId}" class="${styles['word-mark-error-highlight-critical']}"`;
          //     break;
          //   case 'leadername': //领导人姓名检查
          //   case 'leadersort': //领导人排序检查
          //   case 'leadertitle': //领导人职务检查
          //   case 'politicalman': //提及政要
          //     //崩溃
          //     errorWord = `id="word${item.positioningId}" class="${styles['word-mark-error-critical']}"`;
          //     errorWordHighlight = `id="word${item.positioningId}" class="${styles['word-mark-error-highlight-critical']}"`;
          //     console.log('word10846884399415365', item.positioningId);

          //     break;
          // }
          setHtmlValueState(original.replace(errorWord, errorWordHighlight));
        }
      } else {
        item.click = 0;
      }
    });

    setCheckState(checks);
  };

  const renderChecks = (items: any) =>
    items.map((item, index) => {
      let ribbonColor = '#FFC300';
      if (item.repair == 1) {
        ribbonColor = '#0DBC79';
      } else {
        if (item.ignore == 1) {
          ribbonColor = 'blue';
        } else {
          const inspectCategory = item.inspectCategory;
          const inspectTypeEn = item.inspectTypeEn;

          switch (inspectTypeEn) {
            case 'traditionalchinese': //繁简误用
            case 'variantchar': //异体字检查
            case 'transerror': //译文检查
            case 'terms': //不规范名词检查
            case 'keywords': //重点词检查
            case 'ADtime': //公元纪年错误
            case 'historytime': //历史纪年错误
            case 'branchtime': //干支纪年错误
            case 'placenameused': //地名检查（曾用名）
            case 'placenamematch': //地名检查（新旧地名不匹配）
            case 'placenamedivision': //地名检查（所属区 划错误）
            case 'placenamelevel': //地名检查（层级错误）
            case 'nonrecommender': //非推荐词
            case 'errorspace': //多余空格
              //一般
              ribbonColor = '#FFC300';
              break;
            case 'errorwords': //易错词检查
            case 'grammar': //语法检查
            case 'englishmodel': //英文检查
            case 'sentivewords': //敏感词检查
            // case 'punctuation': //标点符号检查
            case 'semrepetition': //语义重复
            case 'politicalterms': //涉政用语错误
            case 'politicalman': //提及政要
              //严重
              ribbonColor = '#FFC300';
              // ribbonColor = '#FFC300';
              break;
            case 'leadername': //领导人姓名检查
            case 'leadersort': //领导人排序检查
            case 'leadertitle': //领导人职务检查
              // case 'politicalman': //提及政要
              //崩溃
              // ribbonColor = '#C70039';
              ribbonColor = '#FFC300';
              break;
          }
          if (inspectCategory === '错误') {
            ribbonColor = '#F5222D';
          }
          console.log(ribbonColor);
        }
      }
      return (
        <a
          key={item.id}
          id={`check${item.positioningId}`}
          href={`#word${item.positioningId}`}
          style={{ textDecoration: 'none', color: 'while', cursor: 'default' }}
        >
          <ProCard
            hoverable
            style={{
              backgroundColor: item.click === 1 ? '#cff2ff' : '',
              color: 'black',
              marginTop: 10,
              marginBottom: 10,
              cursor: 'default',
            }}
            onClick={() => {
              if (item.ignore != 1) {
                wordMark(`#word${item.positioningId}`);
              } else {
                message.warning('已经忽略');
              }
            }}
          >
            <Badge.Ribbon
              text={index + 1}
              placement="start"
              style={{
                marginTop: '-10px',
              }}
              color={ribbonColor}
            >
              <div
                style={{
                  marginLeft: '35px',
                }}
              >
                <Tag color={item.inspectCategory == '可疑' ? ribbonColor : '#F5222D'}>
                  {item.inspectCategory === '可疑' ? '核对' : item.inspectCategory}
                </Tag>
                {item.content}
                {item.lookup && (
                  <>
                    <SwapRightOutlined /> {item.lookup}
                  </>
                )}
              </div>
            </Badge.Ribbon>
            <div
              style={{
                flex: 1,
                marginTop: 16,
                justifyContent: 'space-between',
                display: 'flex',
              }}
            >
              <div
                style={{
                  display: 'inline',
                }}
              >
                <div>原因：{item.content}</div>
                <div>提示：{item.inspectType}</div>
              </div>

              <div
                style={{
                  display: 'inline',
                }}
              ></div>
            </div>
          </ProCard>
        </a>
      );
    });
  const items: CollapseProps['items'] = [];

  if (errorItems.length > 0) {
    items.push({
      key: '1',
      label: <Tag color={'#F5222D'}>错误</Tag>,
      children: renderChecks(errorItems),
    });
  }

  if (checkItems.length > 0) {
    items.push({
      key: '2',
      label: <Tag color={'#FFC300'}>核对</Tag>,
      children: renderChecks(checkItems),
    });
  }
  return (
    <ProCard style={{ marginBlockStart: 8 }} gutter={8}>
      <ProCard bordered>
        <Typography.Title level={3} style={{ textAlign: 'center' }}>
          {name ? name : '暂无标题'}
        </Typography.Title>
        <br />
        {html ? (
          <div
            className={styles['scroll-hidden']}
            style={{
              height: '550px', // 设置固定高度
              overflowY: 'scroll', // 启用垂直滚动
              whiteSpace: 'pre-line',
            }}
            dangerouslySetInnerHTML={{
              __html: `${html}`,
            }}
          />
        ) : (
          <>暂无文章内容</>
        )}
      </ProCard>
      {visibleChecks?.length > 0 && (
        <ProCard colSpan={visibleChecks?.length > 0 ? '30%' : '0%'} bordered>
          <WarningTwoTone twoToneColor="red" /> 检测到疑似问题 {visibleChecks?.length} 处
          <div
            style={{
              height: 615,
              overflowX: 'hidden',
              overflowY: 'scroll',
              marginTop: 10,
              scrollbarWidth: 'none',
              paddingLeft: 10,
              paddingRight: 10,
            }}
          >
            <Collapse defaultActiveKey={['1']} ghost items={items}></Collapse>
          </div>
        </ProCard>
      )}
    </ProCard>
  );
};

export default DetailMonitorArticleContent;
